<template>
  <div class="admin-products">
    <el-card>
      <template #header>
        <div class="header-bar">
          <el-button type="primary" :icon="Plus" @click="handleAdd">
            添加商品
          </el-button>
          
          <div class="search-bar">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索商品"
              clearable
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </div>
        </div>
      </template>
      
      <el-table v-loading="loading" :data="productList" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <img :src="getImageUrl(row.image)" style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">
            <span class="price">¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="{ row }">
            <el-tag :type="row.stock < 10 ? 'danger' : 'success'">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="barcode" label="条形码" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              :type="row.status === 1 ? 'warning' : 'success'" 
              text 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button type="danger" text @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        style="margin-top: 20px; justify-content: center;"
        @size-change="loadProducts"
        @current-change="loadProducts"
      />
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2" :step="0.1" />
        </el-form-item>
        
        <el-form-item label="库存数量" prop="stock">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>
        
        <el-form-item label="最低库存" prop="minStock">
          <el-input-number v-model="form.minStock" :min="0" placeholder="库存预警值" />
        </el-form-item>
        
        <el-form-item label="条形码" prop="barcode">
          <el-input v-model="form.barcode" placeholder="请输入条形码" />
        </el-form-item>
        
        <el-form-item label="商品描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        
        <el-form-item label="商品图片">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            accept="image/*"
          >
            <img v-if="form.image" :src="getImageUrl(form.image)" class="upload-image" />
            <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持jpg、png、gif格式，文件大小不超过5MB</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { getProductList, getCategoryList, addProduct, updateProduct, deleteProduct } from '@/api/product'
import { uploadImage } from '@/api/upload'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 图片上传地址
const uploadUrl = '/api/upload/image'

const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const productList = ref([])
const categories = ref([])

const dialogVisible = ref(false)
const formRef = ref(null)
const submitting = ref(false)
const isEdit = ref(false)

const form = reactive({
  id: null,
  name: '',
  categoryId: null,
  price: 0,
  stock: 0,
  minStock: 10,
  barcode: '',
  description: '',
  image: 'https://via.placeholder.com/200'
})

const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }]
}

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑商品' : '添加商品'
})

onMounted(() => {
  loadProducts()
  loadCategories()
})

const loadProducts = async () => {
  loading.value = true
  try {
    // 修正：使用后端接口所需的参数格式
    const requestData = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchKeyword.value || null
      // 不设置status，查询所有商品（包括上架和下架的）
    }
    
    const res = await getProductList(requestData)
    if (res.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败，请检查后端服务是否启动')
    // 使用模拟数据
    productList.value = Array.from({ length: 10 }, (_, i) => ({
      id: i + 1,
      name: `商品${i + 1}`,
      categoryName: '饮料',
      categoryId: 1,
      price: (Math.random() * 50 + 5).toFixed(2),
      image: 'https://via.placeholder.com/60',
      stock: Math.floor(Math.random() * 100),
      barcode: `69012345${String(i).padStart(5, '0')}`,
      description: '优质商品，值得信赖'
    }))
    total.value = 100
  } finally {
    loading.value = false
  }
}

const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      categories.value = res.data
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
    // 使用模拟数据
    categories.value = [
      { id: 1, name: '饮料' },
      { id: 2, name: '零食' },
      { id: 3, name: '日用品' }
    ]
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadProducts()
}

const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

// 上下架商品
const handleToggleStatus = async (row) => {
  const action = row.status === 1 ? '下架' : '上架'
  try {
    await ElMessageBox.confirm(`确定要${action}该商品吗？`, '提示', {
      type: 'warning'
    })
    
    const submitData = {
      id: row.id,
      status: row.status === 1 ? 0 : 1
    }
    
    const res = await updateProduct(submitData)
    if (res.code === 200) {
      ElMessage.success(`${action}成功`)
      loadProducts()
    } else {
      ElMessage.error(res.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}失败:`, error)
      ElMessage.error(error.response?.data?.message || error.message || `${action}失败`)
    }
  }
}

const handleDelete = async (row) => {
  // 检查商品状态
  if (row.status === 1) {
    ElMessage.warning('请先下架商品再删除')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？删除后不可恢复。', '提示', {
      type: 'warning'
    })
    
    const res = await deleteProduct(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadProducts()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || error.message || '删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 准备提交的数据，确保字段匹配后端
        const submitData = {
          name: form.name,
          categoryId: form.categoryId,
          price: form.price,
          stock: form.stock,
          minStock: form.minStock || 10,
          barcode: form.barcode || null,
          description: form.description || null,
          image: form.image || null,
          status: 1,  // 默认上架
          isHot: 0    // 默认非热销
        }
        
        if (isEdit.value) {
          // 更新时需要包含ID
          submitData.id = form.id
          const res = await updateProduct(submitData)
          if (res.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            loadProducts()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          const res = await addProduct(submitData)
          if (res.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            loadProducts()
          } else {
            ElMessage.error(res.message || '添加失败')
          }
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(error.response?.data?.message || error.message || '操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = null
  form.name = ''
  form.categoryId = null
  form.price = 0
  form.stock = 0
  form.minStock = 10
  form.barcode = ''
  form.description = ''
  form.image = 'https://via.placeholder.com/200'
}

// 图片上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 图片上传成功
const handleUploadSuccess = (response) => {
  if (response.code === 200 && response.data) {
    form.image = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

// 图片上传失败
const handleUploadError = (error) => {
  console.error('图片上传失败:', error)
  ElMessage.error('图片上传失败，请重试')
}

// 获取图片URL（处理相对路径和绝对路径）
const getImageUrl = (url) => {
  if (!url) return 'https://via.placeholder.com/200'
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  // 通过API代理访问图片
  return 'http://localhost:8080' + url
}
</script>

<style lang="scss" scoped>
.admin-products {
  .header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .search-bar {
      display: flex;
      gap: 10px;
    }
  }
  
  .price {
    color: #ff4d4f;
    font-weight: bold;
  }
  
  .image-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;
      
      &:hover {
        border-color: #409eff;
      }
    }
    
    .upload-image {
      width: 178px;
      height: 178px;
      display: block;
      object-fit: cover;
    }
    
    .image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
      line-height: 178px;
    }
  }
  
  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }
}
</style>











